package progress;

import java.util.concurrent.CountDownLatch;

/**
 * 模拟抢票实现
 */
public class TickPiao implements Runnable {
    private CountDownLatch countDownLatch;

    public TickPiao() {
        super();
    }

    public TickPiao(CountDownLatch countDownLatch) {
        this.countDownLatch = countDownLatch;
    }

    int count = 10;
    //记录第几张票
    int countRecord = 0;
    boolean flag = true;

    @Override
    public void run() {
//        System.out.println("当前线程："+Thread.currentThread().getName());
//        try {
//            Thread.sleep(10);
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }finally {
//          countDownLatch.countDown();
//            System.out.println("当前线程："+Thread.currentThread().getName()+"离开");
//        }

        //循环,当票为0时结束
        while (flag) {
//            方法锁
//            countticket();
//            代码块锁即在方法内部实现
            synchronized (this){
                if (count <= 0) {
                    flag = false;
                    return;
                }
                count--;
                countRecord++;
                System.out.println("当线线程：" + Thread.currentThread().getName() + "\t抢到第几张票：" + countRecord + "\t剩余票数：" + count);
                try {
                    Thread.sleep(10);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

        }
    }

    /**
     * 锁分为代码块锁或方法锁
     */
    private synchronized void countticket() {
        if (count <= 0) {
            flag = false;
            return;
        }
        count--;
        countRecord++;
        System.out.println("当线线程：" + Thread.currentThread().getName() + "\t抢到第几张票：" + countRecord + "\t剩余票数：" + count);
        try {
            Thread.sleep(10);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }


}

